# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
 -------------------------------------------------
    File Name:     __init__.py.py
    Description:   浏览器核心模块
 -------------------------------------------------
 """
from playwright.sync_api import sync_playwright


class BrowserManager:
    def __init__(self, headless=True):
        self.playwright = sync_playwright().start()
        self.browser = self.playwright.chromium.launch(headless=headless)
        self.context = None
        self.page = None

    def new_context(self, device="desktop"):
        devices = self.playwright.devices
        self.context = self.browser.new_context(**devices.get(device, {}))
        return self.context

    def new_page(self, url=None):
        if not self.context:
            self.new_context()
        self.page = self.context.new_page()
        if url:
            self.page.goto(url)
        return self.page

    def close(self):
        if self.page: self.page.close()
        if self.context: self.context.close()
        if self.browser: self.browser.close()
        self.playwright.stop()
